package mc.contents.web.common;

import com.alibaba.fastjson.JSON;
import mc.contents.service.ICrawService;
import mc.contents.util.TimeUtils;
import mc.contents.web.AsyncContextFactory;
import mc.contents.web.result.ReturnResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Created by Administrator on 14-12-8.
 */
public abstract class AbstractAsyncListener implements AsyncListener {
    private static Logger log = LoggerFactory.getLogger( AbstractAsyncListener.class );
    private Long id;
    private Long start;
    private String name;

    public AbstractAsyncListener() {

    }

    public AbstractAsyncListener( Long id, Long start, String name ) {
        this.id = id;
        this.start = start;
        this.name = name;
    }

    @Override
    public void onComplete( AsyncEvent event ) throws IOException {
        log.info( "task:{}_{} complete at {}",name,id, TimeUtils.format( new Date() ));
        AsyncContext asyncContext = event.getAsyncContext();
        CommonContext commonContext = AsyncContextFactory.get( name,id );
        if( commonContext!=null ){
            String errMsg = commonContext.isTimeout() ? "craw timeout " : ( commonContext.isError() ? "craw error " : null);
            String resMsg = handleResult( errMsg, commonContext, start );
            //map移除key
            AsyncContextFactory.remove( name,id );
            HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
            responseFront( response, resMsg );
        }
    }

    public abstract String handleResult( String errMsg,CommonContext commonContext,long start );

    @Override
    public void onTimeout( AsyncEvent event ) throws IOException {
        CommonContext commonContext = AsyncContextFactory.get( name,id );
        if( commonContext!=null ){
            commonContext.setTimeout( true );
            commonContext.getContext().complete();
        }
    }

    @Override
    public void onError( AsyncEvent event ) throws IOException {
        log.error( "onError : ", event.getThrowable() );
        CommonContext commonContext = AsyncContextFactory.get( name,id );
        if( commonContext!=null ){
            commonContext.setError( true );
            commonContext.getContext().complete();
        }
    }

    @Override
    public void onStartAsync( AsyncEvent event ) throws IOException {

    }

    private void responseFront ( HttpServletResponse res, String msg ) {
        try{
            res.setStatus( 200 );
            res.setHeader( "Content-type","text/javascript;charset=UTF-8" );
            PrintWriter writer = res.getWriter();
            writer.print( msg );
            writer.flush();
        }catch ( IOException e ){
            log.error( "responseFront error : ",e );
        }
    }

    public String getJsonStr( CommonDisplay display,String errMsg ) {
        ReturnResponse res = new ReturnResponse();
        res.setErrMsg( errMsg );
        res.setResponse( display );
        res.setStatus( 0 );
        return JSON.toJSONString( res );
    }
}
